<template>
  <view class="content">
    <!-- 查询条件 -->
    <view class="search-box">
      <uni-search-bar 
        placeholder="请输入任务标题" 
        v-model="queryParams.title"
        @confirm="search"
      />
      <view class="filter-row">
        <uni-data-select
          v-model="queryParams.productId"
          placeholder="选择产品"
          :localdata="products"
        />
        <uni-data-select
          v-model="queryParams.orderId"
          placeholder="选择订单"
          :localdata="orders"
        />
        <button type="primary" @click="search">搜索</button>
      </view>
    </view>

    <!-- 数据表格 -->
     <!-- 列表展示 -->
        <view class="list-container">
          <view class="list-item" v-for="item in tableData" :key="item.id">
            <view class="item-header">
              <text class="item-title">{{ item.title }}</text>
              <uni-tag :text="statusMap[item.approvalStatus]" 
                      :type="statusTypeMap[item.approvalStatus]"/>
            </view>
            
            <view class="item-body">
              <view class="info-row">
                <text class="info-label">产品：</text>
                <text class="info-value">{{ item.productName }}</text>
              </view>
              <view class="info-row">
                <text class="info-label">订单号：</text>
                <text class="info-value">{{ item.orderCoder }}</text>
              </view>
              <view class="info-row">
                <text class="info-label">数量：</text>
                <text class="info-value">{{ item.actualQty }}{{ item.unit }}</text>
              </view>
            </view>
    
            <view class="item-actions">
              <button class="action-btn" size="mini" @click="showDetail(item)">查看详情</button>
               <!-- 原本删除按钮改为提交按钮，点击后将状态修改为1 -->
                     <button v-if="item.approvalStatus === 0" 
                             class="action-btn" 
                             size="mini" 
                             type="primary"
                             @click="submitItem(item)">提交</button>
            </view>
    
            <!-- 详情展开面板 -->
            <view class="detail-panel" v-if="item.showDetail">
              <view class="detail-row">
                <text class="detail-label">上报时间：</text>
                <text>{{ formatTime(item.reportTime) }}</text>
              </view>
              <view class="detail-row">
                <text class="detail-label">备注：</text>
                <text>{{ item.remark || '无' }}</text>
              </view>
            </view>
          </view>
        </view>

    <!-- 添加按钮 -->
    <view class="add-btn">
      <button type="primary" @click="showAddForm">新建上报</button>
    </view>

    <!-- 添加弹窗 -->
     <uni-popup ref="addForm" type="dialog">
        <uni-popup-dialog mode="form" title="新建任务上报" @confirm="submitForm">
          <uni-forms ref="form" :model="formData" :rules="rules">
            <!-- 新增生产计划选择 -->
            <uni-forms-item label="选择生产计划" name="planningId" required>
              <uni-data-select
                v-model="formData.planningId"
                placeholder="请选择生产计划"
                :localdata="productionPlans"
                @change="handlePlanChange"
              />
            </uni-forms-item>
    
            <!-- 自动填充的字段 -->
            <uni-forms-item label="产品名称">
              <uni-easyinput v-model="formData.productName" disabled />
            </uni-forms-item>
            <uni-forms-item label="订单编号">
              <uni-easyinput v-model="formData.orderCode" disabled />
            </uni-forms-item>
            <uni-forms-item label="计划数量">
              <uni-easyinput v-model="formData.productionQuantity" disabled />
            </uni-forms-item>
    
            <!-- 原有其他字段 -->
            <uni-forms-item label="任务标题" name="title">
              <uni-easyinput v-model="formData.title" />
            </uni-forms-item>
            <uni-forms-item label="实际上报数量" name="actualQty">
              <uni-easyinput v-model="formData.actualQty" type="number">
                <template #right>
                  <uni-data-select v-model="formData.unit" :localdata="units"/>
                </template>
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item label="上报时间">
              <uni-datetime-picker v-model="formData.reportTime"/>
            </uni-forms-item>
          </uni-forms>
        </uni-popup-dialog>
      </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 查询参数
      queryParams: {
        title: '',
        productId: '',
        orderId: ''
      },
 
      // 表格数据
      tableData: [],
      
       // 新增数据项
            productionPlans: [], // 生产计划列表
            statusMap: {
              // 扩展状态映射
              2: '进行中',
              3: '已完成'
            },
            
            // 修改formData结构
            formData: {
              planningId: null,
              productId: null,
              productName: '',
			  orderId:'',
              orderCode: '',
              productionQuantity: 0,
              title: '',
			  scheduleId:'',
              actualQty: null,
              unit: '件',
              reportTime: new Date().toISOString()
            },
      // 数据字典
      products: [], // 改为空数组等待接口填充
      orders: [],
      units: [{text: '件', value: '件'}, {text: '套', value: '套'}],
      statusMap: {
		  0:'草稿',
        1: '待审批',
        2: '已通过',
        3: '已驳回'
      },
      statusTypeMap: {
        0: 'warning',
        1: 'success',
        2: 'error'
      },
	  currentWorkshopId:'',
      
      // 验证规则
    rules: {
            planningId: { rules: [{required: true, errorMessage: '请选择生产计划'}] },
            title: { rules: [{required: true, errorMessage: '请输入标题'}] },
            actualQty: { 
              rules: [
                {required: true, errorMessage: '请输入数量'},
                {validateFunction: (rule, value, data) => value > 0, errorMessage: '数量必须大于0'}
              ]
            }
          }
    }
  },
  onLoad(options) {
    // 如果从上一个页面传入了 workshopId，就赋值给 currentWorkshopId
    if (options.workshopId) {
      this.currentWorkshopId = options.workshopId;
    }
  },
  mounted() {
     this.loadData()
	 this.loadProducts() // 新增产品加载
	 this.loadOrder()
  },
  methods: {
	// 新增产品加载方法
	    async loadProducts() {
	      try {
	        const res = await uni.request({
	          url: 'http://localhost:1003/product/findAllProduct',
	          method: 'GET'
	        })
	        
	        if (res.data.code === 200) {
	          this.products = res.data.data.map(product => ({
	            text: product.productName,
	            value: product.id
	          }))
	        }
	      } catch (e) {
	        console.error('产品加载失败:', e)
	        uni.showToast({ title: '产品数据加载失败', icon: 'none' })
	      }
	    },
		// 新增订单加载方法
		    async loadOrder() {
		      try {
		        const res = await uni.request({
		          url: 'http://localhost:1003/order/findAllOrder',
		          method: 'GET'
		        })
		        
		        if (res.data.code === 200) {
		          this.orders = res.data.data.map(order => ({
		            text: order.orderNumber,
		            value: order.id
		          }))
		        }
		      } catch (e) {
		        console.error('产品加载失败:', e)
		        uni.showToast({ title: '产品数据加载失败', icon: 'none' })
		      }
		    },
	   // 提交方法：将状态修改为1，并调用接口更新后台
	      submitItem(item) {
	        uni.showLoading({ title: '提交中...' });
	        // 示例请求，根据实际接口地址调整
	        uni.request({
	          url: 'http://localhost:1101/reportSummary/updateReportSummary',
	          method: 'POST',
	          header: { 'Content-Type': 'application/json' },
	          data: {
	            id: item.id,
	            approvalStatus: 1,
				workflowId: 1
	          },
	          success: (res) => {
	            if (res.statusCode === 200 && res.data.code === 200) {
	              uni.showToast({ title: '提交成功' });
				   // 向审批表添加记录
				  this.addApprovalRecord(item.id);
	              // 刷新列表数据
	              this.loadData();
	            } else {
	              uni.showToast({ title: res.data.msg || '提交失败', icon: 'none' });
	            }
	          },
	          fail: (err) => {
	            uni.showToast({ title: '网络错误', icon: 'none' });
	          },
	          complete: () => {
	            uni.hideLoading();
	          }
	        });
	      },
		  // 向审批表中添加记录
		  addApprovalRecord(reportId) {
			  const userIdInfo = uni.getStorageSync('userIdInfo');
		    uni.request({
		      url: 'http://localhost:1101/reportProcess/save',
		      method: 'POST',
		      header: { 'Content-Type': 'application/json' },
		      data: {
		        reportId: reportId, // 任务ID
		        approverId: userIdInfo.userId, // 获取审批人ID，可能需要从用户信息中提取
		        approverRoleId: 106, // 获取审批人角色ID
		        approvalStatus: 1, // 初始审批状态：1 同意
		        createdBy: userIdInfo.userId, // 创建人ID
				processId: 0,
				processStep: 0,
				createdAt: this.formData.reportTime,
				updatedAt:this.formData.reportTime
		      },
		      success: (res) => {
		        if (res.statusCode === 200 && res.data.code === 200) {
		          console.log('审批记录添加成功');
		        } else {
		          uni.showToast({ title: res.data.msg || '添加审批记录失败', icon: 'none' });
		        }
		      },
		      fail: (err) => {
		        uni.showToast({ title: '网络错误', icon: 'none' });
		      }
		    });
		  },
	  
	  
     // 加载任务列表
        async loadData() {
          uni.showLoading({ title: '加载中' })
          uni.request({
            url: 'http://localhost:1101/reportSummary',
            method: 'GET',
            data: this.queryParams,
            success: (res) => {
              if (res.statusCode === 200 && res.data.code === 200) {
                this.tableData = res.data.data
              } else {
                uni.showToast({ title: res.data.msg || '请求失败', icon: 'none' })
              }
            },
            fail: (err) => {
              uni.showToast({ title: '网络错误', icon: 'none' })
            },
            complete: () => {
              uni.hideLoading()
            }
          })
        },
	// 加载生产计划
	    async loadProductionPlans() {
	      uni.showLoading({ title: '加载计划' })
	      uni.request({
	        url: 'http://localhost:1003/planning/findAllPlanning',
	        method: 'GET',
			data:{
				status: 3,
				workshopId: this.currentWorkshopId,
			},
	        success: (res) => {
	          if (res.data?.code === 200) {
	            this.productionPlans = res.data.data.map(plan => ({
	              text: `${plan.productName} (${plan.orderCode})`,
	              value: plan.id,
	              rawData: plan
	            }))
	          } else {
	            uni.showToast({ title: res.data?.msg || '加载失败', icon: 'none' })
	          }
	        },
	        fail: (err) => {
	          uni.showToast({ title: '网络错误', icon: 'none' })
	        },
	        complete: () => {
	          uni.hideLoading()
	        }
	      })
	    },
	    // 新增方法：处理计划选择
	    handlePlanChange(value) {
	      const selectedPlan = this.productionPlans.find(p => p.value === value)?.rawData
	      if(selectedPlan) {
	        this.formData = {
	          ...this.formData,
	          productId: selectedPlan.productId,
	          productName: selectedPlan.productName,
	          orderCode: selectedPlan.orderCode,
			  orderId:selectedPlan.orderId,
			  scheduleId:selectedPlan.schedulingId,
	          productionQuantity: selectedPlan.productionQuantity,
	          productionPlanId: selectedPlan.id // 对应MesWorkshopReportSummary中的productionPlanId
	        }
	      }
	    },
    
    // 搜索
    search() {
      this.loadData()
    },
    
    // 显示添加表单
    showAddForm() {
      this.$refs.addForm.open()
    },
    
    // 提交表单
   // 修改后的提交方法
       // 提交表单
           async submitForm() {
             try {
				const userIdInfo = uni.getStorageSync('userIdInfo');
               const valid = await this.$refs.form.validate()
               if (!valid) return
			 
               const submitData = {
                 ...this.formData,
                 approvalStatus: 0,
				 workflowId: 0,
				 createdBy: userIdInfo.userId,
				 createdAt: this.formData.reportTime,
				 updatedAt: this.formData.reportTime,
				 deleted:0
               }
               uni.showLoading({ title: '提交中' })
               uni.request({
                 url: 'http://localhost:1101/reportSummary/addReportSummary',
                 method: 'POST',
                 header: { 'Content-Type': 'application/json' },
                 data: submitData,
                 success: (res) => {
                   if (res.statusCode === 200 || res.data.code === 200) {
                     uni.showToast({ title: '添加成功' })
                     this.$refs.addForm.close()
                     this.loadData()
                   } else {
                     uni.showToast({ title: res.data.msg || '提交失败', icon: 'none' })
                   }
                 },
                 fail: (err) => {
                   uni.showToast({ title: '网络错误', icon: 'none' })
                 },
                 complete: () => {
                   uni.hideLoading()
                 }
               })
             } catch (e) {
               console.error(e)
             }
           },
	      // 在打开弹窗时加载计划
	       showAddForm() {
	         this.loadProductionPlans()
	         this.$refs.addForm.open()
	       },
    // 修改后的查看详情方法
        showDetail(item) {
          this.$set(item, 'showDetail', !item.showDetail)
        },
        // 新增时间格式化方法
         formatTime(time) {
             const date = new Date(time);
             const year = date.getFullYear();
             const month = String(date.getMonth() + 1).padStart(2, '0');
             const day = String(date.getDate()).padStart(2, '0');
             const hours = String(date.getHours()).padStart(2, '0');
             const minutes = String(date.getMinutes()).padStart(2, '0');
             return `${year}-${month}-${day} ${hours}:${minutes}`;
           },
    // 获取产品名称
    getProductName(id) {
      return this.products.find(p => p.value === id)?.text || '-'
    }
  }
}
</script>

<style scoped>
/* 列表样式 */
.list-container {
  padding: 15px;
}

.list-item {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 12px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.item-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.item-body {
  margin-bottom: 12px;
}

.info-row {
  display: flex;
  margin-bottom: 6px;
}

.info-label {
  color: #666;
  min-width: 60px;
}

.info-value {
  color: #333;
}

.item-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.action-btn {
  margin: 0;
  line-height: 1.8;
}

.detail-panel {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #eee;
}

.detail-row {
  display: flex;
  margin-bottom: 6px;
  font-size: 12px;
  color: #666;
}

.detail-label {
  min-width: 70px;
  color: #999;
}
.search-box {
  padding: 15px;
  background: #fff;
}
.filter-row {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}
.add-btn {
  position: fixed;
  bottom: 30px;
  right: 15px;
  z-index: 999;
}
.action-btns {
  display: flex;
  gap: 5px;
}
/* 新增样式 */
.plan-info {
  padding: 10px;
  background: #f5f5f5;
  border-radius: 4px;
  margin-bottom: 15px;
}
.plan-info text {
  display: block;
  color: #666;
  font-size: 14px;
}
</style>